import { Component, OnInit, Input } from '@angular/core';
import { ControlApiService } from '@core/controlApi.service';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../../environments/environment';
declare const go: any;

@Component({
    selector: 'app-controlintelligent',
    templateUrl: './intelligent.component.html',
    styles: [`
        #myDiagramDiv{width:100%;text-align:center;}
        .nodata{height:430px;line-height:430px;font-size:16px;text-align:center;color:#666;}
    `]
})

export class ControlintelligentComponent implements OnInit {
    @Input() queryParams: any;
    @Input() height: any;
    isVisible = false;
    flowCharList = [];
    flowCharTemp = [];
    myDiagram: any;
    singleClick = false;
    clickTimer = null;
    nodata = false;
    stepkey: any;
    title = '';
    stroke = '#424566';
    fill = '#272946';
    color = '#fff';
    arrow = '#1890ff';

    constructor(
        private controlApiService: ControlApiService,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        if (!this.queryParams.DEVTYPEID || !this.queryParams.ALARMTYPE) {
            this.nodata = true;
            return;
        }
        this.getwrongtree(this.queryParams.DEVTYPEID, this.queryParams.ALARMTYPE).subscribe((res: any) => {
            if (res.msg === 'Ok') {
                for (const item of res.data[0]) {
                    this.flowCharList.push({
                        key: item.KEY,
                        treeid: item.TREEID,
                        parent: item.PARENT ? item.PARENT : '',
                        name: item.NAME,
                        locked: '0'
                    });
                }
                this.getwrongNode();
            }
        });
    }

    // 获取故障树节
    getwrongtree(dev, alarm) {
        const url = environment.project + '/emAlarmwrongtree/getwrongtree?devtypeid=' + dev + '&alarmtypeid=' + alarm;
        return this.http.get(url);
    }
    getwrongNode() {
        if (!this.queryParams.ALARMTYPE) {
            return;
        }
        this.getwrongTreeNode(this.queryParams.ALARMTYPE).subscribe((res: any) => {
            if (res.msg === 'Ok') {
                if (res.data[0] || res.data[0] === '') {
                    this.singleClick = true;
                } else {
                    for (const item of res.data[0]) {
                        this.findId(item.NODEID, item.WRONGTREEID);
                    }
                }
                const temp = [];
                for (const item of this.flowCharTemp) {
                    if (temp.indexOf(item) === -1) {
                        temp.push(item);
                    }
                }
                this.flowCharTemp = temp;
                this.goflow();
            }
        });
    }

    // 获取故障树节点ID
    getwrongTreeNode(alarm) {
        const url = environment.project + '/emAlarmwrongtree/getwrongNode?alarmtypeid=' + alarm;
        return this.http.get(url);
    }
    handleOk() {
        this.isVisible = false;
    }

    goflow() {
        const $ = go.GraphObject.make;
        if (this.myDiagram) {
            this.myDiagram.div = null;
        }
        this.myDiagram =
            $(go.Diagram, 'myDiagramDiv', {
                initialContentAlignment: go.Spot.Center, // 居中显示内容
                contentAlignment: go.Spot.Top, // 不能拖动画布
                'undoManager.isEnabled': false, // 打开 Ctrl-Z 和 Ctrl-Y 撤销重做功能
                isReadOnly: true, // 不能拖动节点
                autoScale: go.Diagram.Uniform, // 画布比例自适应
                layout: $(go.TreeLayout, {
                    angle: 90,
                    layerSpacing: 35,
                    setsPortSpot: false,
                    setsChildPortSpot: false,
                    arrangement: go.TreeLayout.ArrangementHorizontal
                })
            });

        this.myDiagram.nodeTemplate =
            $(go.Node, 'Auto',
                {
                    locationSpot: go.Spot.Center,
                    fromSpot: go.Spot.AllSides,
                    toSpot: go.Spot.AllSides
                },
                $(go.Shape, 'RoundedRectangle',
                    {
                        name: 'SHAPE',
                        strokeWidth: 2,
                        stroke: this.stroke,
                        fill: this.fill
                    }
                ),
                $(go.TextBlock,
                    {
                        name: 'TEXTBLOCK',
                        stroke: this.color,
                        margin: 5
                    },
                    new go.Binding('text', 'name')
                ),
                {
                    click: (ev, obj) => {
                        if (this.singleClick) {
                            clearTimeout(this.clickTimer);
                            this.clickTimer = setTimeout(() => {
                                let wrapColor = this.arrow;
                                let pipeColor = this.color;
                                let pipeArray = [10, 10];
                                let arrowColor = this.arrow;
                                let brosh = $(go.Brush, 'Linear', { start: go.Spot.Left, end: go.Spot.Right, 0: this.arrow, 1: this.arrow });
                                const shape = obj.findObject('SHAPE');
                                const text = obj.findObject('TEXTBLOCK');

                                this.stepkey = obj.data.key;
                                if (text.locked === '1') {
                                    text.locked = '0';
                                    brosh = this.stroke;
                                    wrapColor = this.stroke;
                                    pipeColor = this.stroke;
                                    pipeArray = [];
                                    arrowColor = this.stroke;
                                    shape.stroke = this.stroke;
                                    shape.fill = this.fill;
                                } else {
                                    text.locked = '1';
                                    shape.stroke = brosh;
                                    shape.fill = brosh;
                                }

                                this.myDiagram.links.each((link) => {
                                    if (link.data.key == this.stepkey) {
                                        const wrap = link.findObject('WRAP');
                                        const pipe = link.findObject('PIPE');
                                        const arrow = link.findObject('ARROW');
                                        wrap.stroke = wrapColor;
                                        pipe.stroke = pipeColor;
                                        pipe.strokeDashArray = pipeArray;
                                        arrow.fill = arrowColor;
                                    }
                                });
                            }, 250);
                        }
                    },
                    isActionable: true // 去掉点击的边框
                }
            );

        this.myDiagram.linkTemplate =
            $(go.Link,
                {
                    selectable: false, // 用户不能选择链接
                    routing: go.Link.AvoidsNodes,
                    curve: go.Link.JumpGap,
                    corner: 20,
                    reshapable: true,
                    toShortLength: 7
                },
                new go.Binding('points').makeTwoWay(),
                $(go.Shape, { isPanelMain: true, stroke: this.stroke, strokeWidth: 3, name: 'WRAP' }),
                $(go.Shape, { isPanelMain: true, stroke: this.stroke, strokeWidth: 1, name: 'PIPE' }),
                $(go.Shape, { toArrow: 'Triangle', fill: this.stroke, stroke: null, name: 'ARROW' }),

            );
        this.eachLoop(this.myDiagram);

        this.myDiagram.model = $(go.TreeModel, {
            copiesArrays: true,
            copiesArrayObjects: true,
            nodeDataArray: this.flowCharList
        });
        this.eachFlow(10, -1, this.flowCharTemp, this.myDiagram, go.GraphObject.make);
    }
    // 给终极节点ID反推父级
    findId(id, treeid) {
        for (const item of this.flowCharList) {
            if (item.key == id && item.treeid == treeid && item.parent) {
                this.flowCharTemp.unshift(item.key);
                this.flowCharTemp.unshift(item.parent);
                this.findId(item.parent, item.treeid);
            }
        }
    }
    eachFlow(time, length, step, myDiagram, $) {
        if (length !== step.length) {
            setTimeout(() => {
                length = length + 1;
                this.startStep(step[length], myDiagram, $);
                this.eachFlow(time, length, step, myDiagram, $);
            }, time);
        }
    }
    startStep(index, data, $) {
        data.nodes.each((node) => {
            if (node.data.key == index) {
                const shape = node.findObject('SHAPE');
                const brosh = $(go.Brush, 'Linear', { start: go.Spot.Left, end: go.Spot.Right, 0: this.arrow, 1: this.arrow });
                shape.stroke = brosh;
                shape.fill = brosh;
            }
        });
        data.links.each((link) => {
            if (link.data.key == index) {
                const wrap = link.findObject('WRAP');
                const pipe = link.findObject('PIPE');
                const arrow = link.findObject('ARROW');
                wrap.stroke = this.arrow;
                pipe.stroke = this.color;
                pipe.strokeDashArray = [10, 10];
                arrow.fill = this.arrow;
            }
        });
    }
    // 流动效果
    eachLoop(myDiagram) {
        const diagram = myDiagram;
        setTimeout(() => {
            const oldskips = diagram.skipsUndoManager;
            diagram.skipsUndoManager = true;
            diagram.links.each((link) => {
                const shape = link.findObject('PIPE');
                const off = shape.strokeDashOffset - 2;
                shape.strokeDashOffset = (off <= 0) ? 20 : off;
            });
            diagram.skipsUndoManager = oldskips;
            this.eachLoop(diagram);
        }, 100);
    }
}
